<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleCancel" center width="600px">
      <el-form
        ref="editFormRef"
        :validate-on-rule-change="false"
        :model="editForm"
        :rules="rules"
        label-width="100px"
        size="small"
      >
        <el-form-item v-if="model.id" label="巡更点编号" prop="spotCode">
          <el-input placeholder="请输入巡更点编号" v-model="editForm.spotCode" disabled maxlength="32"></el-input>
        </el-form-item>

        <el-form-item label="巡更点名称" prop="spotName">
          <el-input placeholder="请输入巡更点名称或编号" v-model="editForm.spotName" maxlength="32"></el-input>
        </el-form-item>

        <el-form-item label="巡更点类型" prop="spotType">
          <el-select v-model="editForm.spotType" placeholder="请选择巡更点类型" style="width: 100%;">
            <el-option
              v-for="item in spotTypeList"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="!model.id" label="是否有效" prop="spotEnable">
          <el-select v-model="editForm.spotEnable" placeholder="请选择是否有效" style="width: 100%;">
            <el-option :value="1" label="是"></el-option>
            <el-option :value="0" label="否"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="楼栋" prop="spotBuilding">
          <el-select
            ref="buildRef"
            v-model="editForm.spotBuilding"
            clearable
            placeholder="请选择楼栋"
            @change="buildChange"
          >
            <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="楼层" prop="spotFloor">
          <el-select
            ref="fllorRef"
            v-model="editForm.spotFloor"
            clearable
            placeholder="请选择楼层"
            @change="floorChange"
          >
            <el-option v-for="item in floorList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="区域或房间" prop="spotRoom">
          <el-select
            ref="roomRef"
            v-model="editForm.spotRoom"
            clearable
            placeholder="请选择区域或房间"
            @change="roomChange"
          >
            <el-option v-for="item in roomList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="点位坐标" prop="positionStr">
          <el-button plain v-if="!editForm.positionStr" @click="positionFocus(false)">尚未撒点</el-button>
          <el-input
            v-else
            ref="positionInput"
            placeholder="请设置坐标"
            @focus="positionFocus(true)"
            v-model="editForm.positionStr"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel" size="small">取 消</el-button>
        <el-button type="primary" @click="handleOk('editFormRef')" size="small">确 定</el-button>
      </div>
    </el-dialog>

    <dot-modal ref="dotModal" @dotModalOk="dotModalOk"></dot-modal>
  </div>
</template>

<script>
import { addSpot, updateSpot } from '../js/patrol'
import { getListByTag } from '../js/monitor'
import dotModal from './DotModal'
import { spotTypeList } from '../js/constants'

export default {
  name: 'PositionModal',
  data () {
    return {
      title: '创建巡更点',
      dialogVisible: false,
      model: {},
      editForm: {
        spotCode: '',
        spotName: '',
        spotType: '',
        spotEnable: '',
        spotBuilding: null,
        spotFloor: null,
        spotRoom: null,
        positionStr: ''
      },
      rules: {
        spotCode: [{ required: true, message: '请输入巡更点编号!' }],
        spotName: [{ required: true, message: '请输入巡更点名称或编号!' }],
        spotType: [{ required: true, message: '请输入巡更点类型!' }],
        spotEnable: [{ required: true, message: '请选择是否有效!' }],
        spotBuilding: [{ required: true, message: '请选择楼栋!' }],
        spotFloor: [{ required: true, message: '请选择楼层!' }],
        positionStr: [{ required: true, message: '请设置点位坐标!' }]
      },
      buildList: [], // 楼栋
      floorList: [], // 楼层
      roomList: [], // 区域或房间
      spotTypeList
    }
  },
  components: { dotModal },
  methods: {
    // 新增
    add () {
      this.edit({})
    },

    // 编辑
    edit (record) {
      this.dialogVisible = true
      this.model = Object.assign({}, record)
      this.$nextTick(() => {
        this.getListByTag(0, 1, 'buildList')
      })
      if (record.id) {
        this.title = '编辑巡更点'
        const { spotBuilding, spotFloor, spotPositionX, spotPositionY } = record
        this.$nextTick(() => {
          if (spotBuilding) this.getListByTag(spotBuilding, 2, 'floorList')
          if (spotFloor) {
            this.getListByTag(spotFloor, 3, 'roomList')
            this.getListByTag(spotFloor, 4, 'roomList')
          }
          Object.assign(this.editForm, this.$pick(this.model, 'spotCode', 'spotName', 'spotType', 'spotEnable'))
          this.editForm.positionStr = `${spotPositionX},${spotPositionY}`
        })
      } else {
        this.title = '创建巡更点'
      }
    },

    // 提交表单
    handleOk (editFormRef) {
      this.$refs[editFormRef].validate(async valid => {
        if (valid) {
          let res, msg
          const posTempArr = this.editForm.positionStr.split(',')
          const spotBuildingName = this.$refs.buildRef.selectedLabel
          const spotFloorName = this.$refs.fllorRef.selectedLabel
          const spotRoomName = this.$refs.roomRef.selectedLabel
          const params = {
            ...this.editForm,
            spotRoom: this.editForm.spotRoom ? this.editForm.spotRoom : null,
            spotPositionX: posTempArr[0],
            spotPositionY: posTempArr[1],
            spotBuildingName,
            spotFloorName,
            spotRoomName,
            positionStr: undefined
          }
          if (!this.model.id) {
            res = await addSpot({ ...params, spotCode: undefined })
            msg = '保存成功！'
          } else {
            res = await updateSpot({ ...params })
            msg = '修改成功！'
          }
          if (res.code === 0) {
            this.$message.success(msg)
          } else {
            this.$message.warning(res.msg)
          }
          this.$emit('ok')
          this.handleCancel()
        }
      })
    },

    // 获取楼层信息
    // parentId: 上级id, tag: 1:楼栋 2:楼层 3:楼层区域 4:房间, arr: 保存的数组
    async getListByTag (parentId, tag, arr) {
      const params = {
        parentId,
        tag,
        tenantNo: this.$ls.get('User-Info').tenantNo
      }
      const { data } = await getListByTag(params)
      if (tag === 3 || tag === 4) {
        this[arr] = [...this[arr], ...data]
      } else {
        this[arr] = data
      }
      if (this.model.id) {
        if (tag === 1) this.editForm.spotBuilding = this.model.spotBuilding
        if (tag === 2) this.editForm.spotFloor = this.model.spotFloor
        if (tag === 3 || tag === 4) this.editForm.spotRoom = this.model.spotRoom
      }
    },
    // 楼栋改变
    buildChange (val) {
      this.floorList = []
      this.roomList = []
      this.editForm.spotFloor = ''
      this.editForm.spotRoom = ''
      if (val) {
        this.getListByTag(val, 2, 'floorList')
      }
    },
    // 楼层改变
    floorChange (val) {
      this.roomList = []
      this.editForm.spotRoom = ''
      if (val) {
        this.getListByTag(val, 3, 'roomList')
        this.getListByTag(val, 4, 'roomList')
      }
    },
    // 房间改变
    roomChange (val) {
      if (val) {
        let { mapX, mapY } = this.roomList.filter(e => e.id === val)[0]
        if (mapX && mapY && !this.editForm.positionStr) {
          this.editForm.positionStr = `${mapX},${mapY}`
        }
      }
    },
    // 获取焦点弹框
    positionFocus (flag) {
      console.log(flag)
      let row = {}
      const { spotFloor, spotName } = this.editForm
      if (!spotFloor) return this.$message.info('请先选择楼层!')
      row['mapUrl'] = this.floorList.filter(e => e.id === spotFloor)[0].mapUrl
      row['spotName'] = spotName || '巡'
      let tempArr = this.editForm.positionStr.split(',')
      if (tempArr.length === 2) {
        row['roomX'] = tempArr[0]
        row['roomY'] = tempArr[1]
      }
      this.$refs.dotModal.add(row)
      if (flag) {
        this.$nextTick(() => {
          this.$refs.positionInput.blur()
        })
      }
    },
    dotModalOk (val) {
      this.editForm.positionStr = val
    },

    // 取消
    handleCancel () {
      this.dialogVisible = false
      this.editForm.spotEnable = ''
      this.$refs.editFormRef.resetFields()
      this.buildList = []
      this.floorList = []
      this.roomList = []
    }
  }
}
</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
</style>
